#!/bin/bash

if [ ! -e last_log_filename ]; then
    echo Server stoped.
    exit 0
fi

last_log_file=$(cat last_log_filename)
main_worker_pid=$(./find_main_worker_pid.py)

function dump_ps_pythons() {
    ps -ef | grep python3 >> $1
}

echo "Shutting down server at" $(date) >> $last_log_file
echo "before kill" >> $last_log_file
dump_ps_pythons $last_log_file
if [ $? == 0 ]; then
    kill $main_worker_pid
fi

wait_time=10

for (( i=0; i<wait_time; i=i+1 )); do
    found=$(grep -c "\[INFO\] Server Stopped" $last_log_file)
    if [ $found == 1 ]; then
        echo "Server stopped."
        break
    fi
    sleep 3
done

echo "after kill" >> $last_log_file
dump_ps_pythons $last_log_file

rm last_log_filename

sleep 1